import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        openid:"3SQh9NlhcuqiCaiZ",
        session_key:'CySmdsu8Uk6g5ylDi922wM4u4ChPJf8X',
		userInfo:'',
		userPhone:'',
		hasLogin: false,
		loginProvider: "",
		testvuex:false,
    },
    mutations: {
        changeOpenid(state,cont){
            //单一的改变某一个变量
            console.log(state)
            console.log(cont)
            state.openid = cont;
        },
        changeHasLogin(state,contObj){
            //通过传入的变量去改变对应的全局变量
            console.log(state)
            console.log(cont)
            state.hasLogin = contObj;
        },
		login(state, provider) {
			state.hasLogin = true;
			state.loginProvider = provider;
		},
		logout(state) {
			state.hasLogin = false
			state.openid = null
		},
		setOpenid(state, openid) {
			state.openid = openid
		},
		setTestTrue(state){
			state.testvuex = true
		},
		setTestFalse(state){
			state.testvuex = false
		}
    },
    actions:{
        copeFun:function(context,mData){
            context.commit('copy',mData)
        },
        changeFun:function(context,obj){
            context.commit('change',obj)
        },
		getUserOpenId: async function ({
			commit,
			state
		}) {
			return await new Promise((resolve, reject) => {
				if (state.openid) {
					resolve(state.openid);
				} else {
					uni.login({
						success: (data) => {
							commit('login')
							setTimeout(function () { //模拟异步请求服务器获取 openid
								const openid = '123456789'
								console.log('uni.request mock openid[' + openid + ']');
								commit('setOpenid', openid)
								resolve(openid)
							}, 1000)
						},
						fail: (err) => {
							console.log('uni.login 接口调用失败，将无法正常使用开放接口等服务', err)
							reject(err)
						}
					})
				}
			})
		}
    }
})

export default store